import UIKit

extension UIColor {

  /// 根据十六进制字符串创建 UIColor
  /// - Parameter hex: 支持 "#RRGGBB"、"RRGGBB"、"#RGB"、"RGB" 格式
  convenience init?(hex: String) {
    var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    // 去掉开头的 #
    if hexString.hasPrefix("#") {
      hexString.remove(at: hexString.startIndex)
    }

    // 处理简写 "RGB" -> "RRGGBB"
    if hexString.count == 3 {
      let r = hexString[hexString.startIndex]
      let g = hexString[hexString.index(hexString.startIndex, offsetBy: 1)]
      let b = hexString[hexString.index(hexString.startIndex, offsetBy: 2)]
      hexString = "\(r)\(r)\(g)\(g)\(b)\(b)"
    }

    // 必须是6位
    guard hexString.count == 6 else { return nil }

    // 转成整数
    var rgbValue: UInt64 = 0
    Scanner(string: hexString).scanHexInt64(&rgbValue)

    let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
    let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
    let blue = CGFloat(rgbValue & 0x0000FF) / 255.0

    self.init(red: red, green: green, blue: blue, alpha: 1.0)
  }
}
